package com.example.grpcquick;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import com.example.grpcquick.AddServiceGrpc.AddServiceImplBase;
import com.example.grpcquick.AddRequest;
import com.example.grpcquick.AddReply;

import java.io.IOException;

public class AddServer extends AddServiceImplBase {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 监听端口，暴露服务
        int port = 9999;
        Server server = ServerBuilder.forPort(port)
                .addService(new AddServer())
                .build()
                .start();
        server.awaitTermination();
        System.out.println("server start at " + port);

//        while (true) {
//            // 保持主线程不要终止
//        }
    }

    @Override
    public void add(AddRequest request, StreamObserver<AddReply> responseObserver) {
        // 具体的业务过程
        int result = myAdd(request.getA(), request.getB());
        // onNext()
        responseObserver.onNext(AddReply.newBuilder()
                .setRes(result)
                .build());
        // onCompleted()
        responseObserver.onCompleted();
    }

    private int myAdd(int a, int b) {
        return a + b;
    }
}
